#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project:     server
# @File:        user_serv.py
# @Author:      Fan GuiChuan
# @Date:        2025/9/3 9:06
# @Version:     Python3.7
# @Description:
import hashlib
import json
from datetime import datetime, timedelta

from flask import request
from app.models.models import User
from app.routes.auth import gen_token

class UserServ:
    """
    模版管理数据操作类
    """
    def __init__(self, logger):
        self.logger = logger

    def registered_user(self):
        user_data = request.json
        # {'username': 'fgc', 'phone': '13654918696', 'verifyCode': '123456', 'password': '123ABCdef*', 'repeatPassword': '123ABCdef*'}
        self.logger.debug(f'register data: {user_data}')

        # basic validation
        username = (user_data.get('username') or '').strip()
        phone = (user_data.get('phone') or '').strip()
        password = user_data.get('password')
        repeat = user_data.get('repeatPassword')

        if not username:
            return False, '用户名不能为空。'
        if not phone:
            return False, '手机号不能为空。'
        if not password or not repeat:
            return False, '请输入密码并确认。'
        if password != repeat:
            return False, '两次输入的密码不一致。'

        # check existing user
        existing = User.query.filter_by(user_name=username).first()
        if existing:
            return False, '用户名已存在，请选择其他用户名。'

        # hash password (sha256)
        sha = hashlib.sha256()
        sha.update(password.encode('utf-8'))
        hashed = sha.hexdigest()

        # default roles and permissions
        roles = json.dumps(["user"])
        permissions = json.dumps([])

        try:
            new_user = User(user_name=username, password=hashed, user_nick_name=username, roles=roles, permissions=permissions)
            # attach to session and commit
            from app.models.models import db
            db.session.add(new_user)
            db.session.commit()

            # generate token and response payload
            token = gen_token()
            expires_date = datetime.now() + timedelta(days=1)
            data = {
                'avatar': '',
                'username': username,
                'nickname': new_user.user_nick_name,
                'roles': json.loads(new_user.roles),
                'permissions': json.loads(new_user.permissions),
                'accessToken': token,
                'refreshToken': token,
                'expires': expires_date.strftime('%Y/%m/%d 00:00:00')
            }
            return True, data
        except Exception as e:
            self.logger.exception('注册用户时发生错误')
            try:
                db.session.rollback()
            except Exception:
                pass
            return False, '注册失败，服务器内部错误。'

    def login_by_username(self):
        login_data = request.json
        self.logger.debug(f'login data: {login_data}')
        username = login_data['username']
        password = login_data['password']

        user = User.query.filter(User.user_name == username and User.password == password).first()
        if user:
            token = gen_token()
            expires_date = datetime.now() + timedelta(days=1)
            data = {
                    'avatar': '',
                    'username': username,
                    'nickname': user.user_nick_name,
                    'roles': json.loads(user.roles),
                    'permissions': json.loads(user.permissions),
                    'accessToken': token,
                    'refreshToken': token,
                    'expires': expires_date.strftime('%Y/%m/%d 00:00:00')
                }
            self.logger.debug(data)
            return True, data
        else:
            return False, '用户名或密码不正确，请检查后重试。'
